﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;

namespace Lebah
{
    public abstract class BaseDevice
    {
        private SerialPort _serialPort;
        private Queue _sendMessages;
        private bool _isRunning;
        private Thread _backProcess;

        public event EventHandler ReceivedData;
        public event EventHandler ReceivedSignal;

        public string Port { set; get; }
        public int BaudRate { set; get; }
        protected BaseDevice()
        {
            _isRunning = false;
        }

        protected virtual void OnReceivedData(ReceivedDataEventArgs e)
        {
            EventHandler handler = ReceivedData;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        protected virtual void OnReceivedSignal(ReceivedDataEventArgs e)
        {
            EventHandler handler = ReceivedSignal;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public void Open()
        {
            if (_isRunning)
                return;

            if (_serialPort == null)
                _serialPort = new SerialPort(Port);
            if (BaudRate > 0)
                _serialPort.BaudRate = BaudRate;

            if (_backProcess == null)
                _backProcess = new Thread(new ThreadStart(ProcessMessage));

            _backProcess.Start();

            _serialPort.DataReceived += SerialPortDataReceived;
            _serialPort.Open();
                        
            if (_isRunning)
                Close();
        }

        
        public void Close()
        {
            _serialPort.Close();
            _isRunning = false;
        }

        #region "Background process"

        private void ProcessMessage()
        {

        }
        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
        }
        #endregion

    }
}
